package util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSource;

public class DBPoolUtils {
	
	// 1.创建一个私有的连接池
	private static DataSource dataSource;
	
	static {
		// 2.从属性文件中得到属性值
		try {
			Properties prop = new Properties();
			prop.load(new FileInputStream("./jdbc.properties"));
			String driver = prop.getProperty("jdbc.driver");
			String url = prop.getProperty("jdbc.url");
			String user = prop.getProperty("jdbc.user");
			String password = prop.getProperty("jdbc.password");
			String initSize = prop.getProperty("jdbc.initSize");
			String minSize = prop.getProperty("jdbc.minSize");
			String maxSize = prop.getProperty("jdbc.maxSize");
			String connTimeout = prop.getProperty("jdbc.connTimeout");
			String queryTimeout = prop.getProperty("jdbc.queryTimeout");
			
			// 3.创建druid连接池
			DruidDataSource dds = new DruidDataSource();
			dds.setDriverClassName(driver);
			dds.setUrl(url);
			dds.setUsername(user);
			dds.setPassword(password);
			dds.setInitialSize(Integer.valueOf(initSize));
			dds.setMinIdle(Integer.valueOf(minSize));
			dds.setMaxActive(Integer.valueOf(maxSize));
			dds.setLoginTimeout(Integer.valueOf(connTimeout));
			dds.setQueryTimeout(Integer.valueOf(queryTimeout));
			
			// 4.给dataSource赋值
			dataSource = dds;
			
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws SQLException {
		return dataSource.getConnection();
	}
	
	// 增删改的方法
	public static int iud(Connection c,String sql,Object...args) throws SQLException {
		PreparedStatement ps = c.prepareStatement(sql);
		// 判断sql文中的?个数和args参数个数一样
		if(sql.chars().filter(ch -> ch=='?').count() != args.length) {
			throw new SQLException("参数个数不对");
		}else {
			for(int i = 1; i <= args.length; i++) {
				ps.setObject(i, args[i-1]);
			}
		}
		return ps.executeUpdate();
	}
	
	// 查询的方法
	public static ResultSet query(Connection c,String sql,Object...args) throws SQLException {
		PreparedStatement ps = c.prepareStatement(sql);
		if(sql.chars().filter(ch -> ch=='?').count() != args.length) {
			throw new SQLException("参数个数不对");
		}else {
			for(int i = 1; i <= args.length; i++) {
				ps.setObject(i, args[i-1]);
			}
		}
		return ps.executeQuery();
	}
}
